var marker;
var newlat;
var newlon;
var oktobuildbase = false;
var satmarkers = [];
var warmarkers =[];
var terdistance;
var BASEURL = "http://global-dominator.appspot.com/";
//var BASEURL = "http://localhost:8888/";
var showTerritoryOnMove = false;
var map=null;
var warMap=null;
var infoWindow;
var map;

var enemyMap;
//var terClusterer;

function closeInfo()
{
if (null != marker)
	{
	marker.setMap(null);
	}
	
	if(null!=infoWindow)
	{
	infoWindow.close();
	}
}

function initializeMap() {
	if(!google) return;
	if (null != map) {
		google.maps.event.trigger(map, 'resize')
		return;
	}
	
	var mapDiv = document.getElementById('territory_map');
	var latLng = new google.maps.LatLng(homeLat,homeLon);
	 map = new google.maps.Map(mapDiv, {  center: latLng,   zoom: 10,
	mapTypeId: google.maps.MapTypeId.ROADMAP,   mapTypeControl: false,  
	mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU	    },
	navigationControl: true,    navigationControlOptions: {    style: google.maps.NavigationControlStyle.SMALL    }
	});
 	
    var markerImage = new google.maps.MarkerImage(BASEURL + 'images/maps/homebig.png',   new google.maps.Size(128, 128));
  	var hMarker = new google.maps.Marker({ position: latLng,  map: map,  icon: markerImage,    title: 'My Home'  });

	google.maps.event.addListener(hMarker, 'click', function(event) {
			$('#territory_hint').show();
			$('#depResult').hide();
		$('#depcostpanel').hide();
closeInfo();
	
	});
	
	
	
  	google.maps.event.addListener(map, 'click', function(event) {
		if(null==event.latLng) return;	
closeInfo();
	newlat= event.latLng.lat();
	newlon=event.latLng.lng();
		terdistance = calculateDistance(homeLat,newlat, homeLon, newlon);
		var simage = BASEURL + "images/maps/construction.png";
		var markerImage = new google.maps.MarkerImage(simage,   new google.maps.Size(128, 128));
		marker = new google.maps.Marker({ position: event.latLng,    draggable: false,icon: markerImage,map:map    });
		infoWindow = new google.maps.InfoWindow({    content: "Home is " + terdistance + " miles away"  });
		infoWindow.open(map,marker);
		showTerritoryInfo(terdistance);
		$('#depResult').hide();
		$('#depcostpanel').show();
	});

google.maps.event.addListener(map, 'dragend', function(event) {
		if (showTerritoryOnMove) {	showLocations(map,true);		}
	});

//terClusterer = new MarkerClusterer(map);
	google.maps.event.addListenerOnce(map, 'idle', delayShow);
google.maps.event.trigger(map, 'resize')
}

function delayShow()
{
showLocations(map,true);
}
function showLocations(thismap,allshow) {
var latsouth = 0;
	var lonsouth = 0;
	var latnorth = 0;
	var lonnorth = 0;
closeInfo();

for(var mk=0;mk<satmarkers.length;mk++)
	{
	satmarkers[mk].setMap(null);
	}
	satmarkers= [];
	$.get("getpersonlocation/get", {
		nlat : latnorth,
		nlon : lonnorth,
		slat : latsouth,
		slon : lonsouth
	}, function(rtnmsg) {
		
		var counter = 0;
		
		for ( var prop in rtnmsg) {
			
			drawMarker(rtnmsg[prop], counter, prop, thismap);
		if (++counter > 50) {
				showTerritoryOnMove = true;
				break;
			}
		}
	});

}

function drawMarker(latlng, counter, depPointer, thismap) {
	var points = latlng.split("/");
	//points 3 should contain the kind of location! captured = 3 FIXME
	var markerImage = new google.maps.MarkerImage(BASEURL + "images/maps/satellitebig.png",   new google.maps.Size(128, 128));
	var latLng = new google.maps.LatLng(points[0], points[1]);
	var smarker = new google.maps.Marker({ position: latLng,    draggable: false,icon: markerImage,map:thismap    });
	satmarkers.push(smarker);
	google.maps.event.addListener(smarker, 'click', function(event) {
			getDeploymentStat(counter, depPointer);
	});

}

function getDeploymentStat(counter, locPointer) {
	$('#depResult').html("<img	src='images/loading/loading1.gif' />");

	closeInfo();
	
	infoWindow = new google.maps.InfoWindow({    content: "Choose the amount of army you want to deploy here"  });
	infoWindow.open(map,satmarkers[counter]);
	
	
	$('#depResult').load('getdeployment/get', {
		locID : locPointer
	});
	
	$('#depResult').show();
	$('#depcostpanel').hide();
	$('#territory_hint').hide();
}




function initializeWarMap() {
	if(!google) return;
	if (null != warMap) {
		google.maps.event.trigger(warMap, 'resize');
		return;
	}

	var mapDiv = document.getElementById('warmap_canvas');
	
	warMap = new google.maps.Map(mapDiv, {
          center: new google.maps.LatLng(homeLat, homeLon),
          zoom: 1,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
 	
	google.maps.event.addListener(warMap, 'dragend', function(event) {
		//showWarLocations(warMap);
	});
	
google.maps.event.addListenerOnce(warMap, 'idle', showWarLocations);
google.maps.event.trigger(warMap, 'resize');

var controlDiv = document.createElement('DIV');
controlDiv.style.padding = '5px';
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to set the map to Home';
controlDiv.appendChild(controlUI);
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '12px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'Search for more enemies';
controlUI.appendChild(controlText)

google.maps.event.addDomListener(controlUI, 'click', function() {
	showLoading();
	showWarLocations(warMap);
	
  });

warMap.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);
	}



function showWarLocations() {
var bounds = warMap.getBounds();
	var sw = bounds.getSouthWest();
	var ne = bounds.getNorthEast();

	var latsouth = sw.lat();
	var lonsouth = sw.lng();

	var latnorth = ne.lat();
	var lonnorth = ne.lng();
	for(var mk=0;mk<warmarkers.length;mk++)
	{
		warmarkers[mk].setMap(null);
	}

	warmarkers=[];
	$.getJSON("getallcombatant/get", {
		nlat : latnorth,
		nlon : lonnorth,
		slat : latsouth,
		slon : lonsouth,
		hc : hc
	}, function(rtnmsg) {
		var counter = 0;
		
		var cordinates;
		for (cordinates in rtnmsg) {
				drawWarMarker(cordinates, counter, rtnmsg[cordinates]);
				if (++counter > 500) {
				break;
			}
		}
		hideLoading();
	});

}

function drawWarMarker(cordinates, counter, locID) {
	var points = cordinates.split("/");
	var markerImage = new google.maps.MarkerImage(BASEURL + "images/maps/enemymarker.png",   new google.maps.Size(128, 128));
	var latLng = new google.maps.LatLng(points[0], points[1]);
	var smarker = new google.maps.Marker({ position: latLng,    draggable: false,icon: markerImage,map:warMap , title: 'My Satellite City'   });
	warmarkers.push(smarker);
	
	google.maps.event.addListener(smarker, 'click', function(event) {
			getCombatantStat(counter, locID);
	});
	
	
}
function getCombatantStat(counter, locPointer) {
	$('#enemypanel').html("<img	src='images/loading/loading1.gif' />");
	var personstats = locPointer.split("/");
	$('#enemypanel').load('getcombatant/get', {
		locID : personstats[0],
		pid:personstats[1]
	});

	if(infoWindow!=null)
infoWindow.close();

infoWindow = new google.maps.InfoWindow({    content: "Choose this enemy or click on another icon to fight"  });
infoWindow.open(warMap,warmarkers[counter]);
}

function calculateDistance(lat1, lat2, lon1, lon2) {
	var R = 6371000; // meters
  var dLat = (lat2-lat1) * Math.PI / 180;
  var dLon = (lon2-lon1) * Math.PI / 180;
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +  Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 )*   Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return Math.round(d/10000); 
  
}

function showTerritoryInfo(distance) {

	var iter = 0;
	oktobuildbase = true;
	for (iter = 0; iter < 6; iter++) {
		var cost = distance * (iter + 1);
		$('#tcost' + iter).html(cost);
		if (resources[iter][1] - cost < 0) {
			$('#tdcost' + iter).html(
					"You need " + (cost - resources[iter][1]) + " more ");
			oktobuildbase = false;
		} else {
			$('#tdcost' + iter).html("&nbsp;");
		}
	}
	$('#territory_hint').hide();
	$('.depcostpanel').show();
}


